package com.woniu.map.remote;

import com.alibaba.cloud.commons.lang.StringUtils;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.woniu.internalcommon.response.WeatherForResponse;
import com.woniu.internalcommon.response.WeatherLiveResponse;
import com.woniu.map.remote.url.WeatherUrl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Service
@Slf4j
public class WeatherClient {

    @Autowired
    private WeatherUrl weatherUrl;
    @Autowired
    private RestTemplate restTemplate;
    /**
     * 获取天气信息
     * @param city 城市编码
     * @param isForecast true 获取预报数据，false 获取实时数据
     * @return
     */
    public  List<?> getWeather(String city, Boolean isForecast)
    {
        String weatherUrl = this.weatherUrl.
                buildWeatherUrl(city, isForecast);

        log.info("查询天气，请求数据：{}",weatherUrl);
        ResponseEntity<String> forEntity = restTemplate.getForEntity(weatherUrl, String.class);

        return parseWeather(forEntity.getBody(), isForecast);
    }
     /**
     * 解析天气数据
     * @param body
     * @param isForecast
     * @return 实体response
     */
    public List<?> parseWeather(String body, Boolean isForecast) {
        log.info("天气服务响应："+body);
        if (StringUtils.isEmpty( body)){
            throw new IllegalArgumentException("天气服务响应失败");
        }
        JSONObject respon = JSONObject.parseObject( body);

       if (!respon.get("infocode").equals("10000")){
           throw new IllegalArgumentException("参数错误");
       }


        return  isForecast?
                   respon.getJSONArray("forecasts")
                           .getJSONObject(0)
                           .getJSONArray("casts")
                            .toList(WeatherForResponse.class) :
                    respon.getJSONArray("lives")
                       .toList(WeatherLiveResponse.class);





    }




}
